package com.file.parser.socialsecurity;


import com.file.bo.ResponseData;
import com.file.bo.socialsecurity.AnhuiIndividualRecordSheet;
import com.file.bo.socialsecurity.AnhuiInsuranceParticipation;
import com.file.constant.ErrorCode;
import com.file.parser.BasePdfParser;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.SpreadsheetDetectionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class AnhuiSocialSecurityPdfParser extends BasePdfParser {

    public ResponseData<String> parseAnhuiSocialSecurityPdfToJson(String daId, String filePath) {
        log.info("parseAnhuiSocialSecurityPdfToJson started, daId:{}", daId);
        String json = null;

        try {
            if (filePath.contains("cbzm")) {
                AnhuiInsuranceParticipation anhuiInsuranceParticipation = parseAnhuiInsuranceParticipation(filePath, daId);
                json = JsonUtils.convertObjectToJson(anhuiInsuranceParticipation);
            } else if (filePath.contains("qyd")) {//NOSONAR
                AnhuiIndividualRecordSheet anhuiIndividualRecordSheet = parseAnhuiIndividualRecordSheet(filePath);
                json = JsonUtils.convertObjectToJson(anhuiIndividualRecordSheet);//NOSONAR
            } else {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAnhuiSocialSecurityPdfToJson failed, new type not supported");
                return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAnhuiSocialSecurityPdfToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAnhuiSocialSecurityPdfToJson completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AnhuiInsuranceParticipation parseAnhuiInsuranceParticipation(String filePath, String daId) {
        AnhuiInsuranceParticipation anhuiInsuranceParticipation = parseAnhuiInsuranceParticipationHeader(filePath, daId);
        List<List<String>> rowList = parseFileToRowList(filePath);
//        for (List<String> cellList : rowList) {
//            System.out.println(cellList);
//        }

        parseListToBO(rowList, anhuiInsuranceParticipation);
        return anhuiInsuranceParticipation;
    }

    private AnhuiInsuranceParticipation parseAnhuiInsuranceParticipationHeader(String filePath, String daId) {
        AnhuiInsuranceParticipation anhuiInsuranceParticipation = new AnhuiInsuranceParticipation();
        String pdfText = parsePdfHeaderText(filePath)
                .replace(System.getProperty("line.separator", "\n"), StringUtils.EMPTY);
//        System.out.println(pdfText);

        String name = pdfText.substring(pdfText.lastIndexOf("参保人：") + 4, pdfText.lastIndexOf("性别：")).trim();
        String sex = pdfText.substring(pdfText.lastIndexOf("性别：") + 3, pdfText.lastIndexOf("身份证号码：")).trim();
        String idNo = pdfText.substring(pdfText.lastIndexOf("身份证号码：") + 6, pdfText.lastIndexOf("在我市参加社会保险情况")).trim();
        String notes = pdfText.substring(pdfText.lastIndexOf("注：") + 2, pdfText.lastIndexOf("社会保险征缴稽核中心")).trim();
        String printTime = pdfText.substring(pdfText.lastIndexOf("社会保险征缴稽核中心") + 10).trim().replace(" ", "");

        anhuiInsuranceParticipation.setName(name);
        anhuiInsuranceParticipation.setSex(sex);
        anhuiInsuranceParticipation.setIdNo(idNo);
        anhuiInsuranceParticipation.setName(name);
        anhuiInsuranceParticipation.setNotes(notes);
        anhuiInsuranceParticipation.setPrintTime(printTime);

        return  anhuiInsuranceParticipation;
    }

    private AnhuiIndividualRecordSheet parseAnhuiIndividualRecordSheet(String filePath) { //NOSONAR
        AnhuiIndividualRecordSheet anhuiIndividualRecordSheet = new AnhuiIndividualRecordSheet();
        return anhuiIndividualRecordSheet;
    }

    private void parseListToBO(List<List<String>> rowList, AnhuiInsuranceParticipation anhuiInsuranceParticipation) {
        List<AnhuiInsuranceParticipation.PaymentDetail> paymentDetailList = new ArrayList<>();

        for (List<String> cellList : rowList) {
            if (StringUtils.equals(cellList.get(0), "参保险种")) {
                continue;
            }
            AnhuiInsuranceParticipation.PaymentDetail paymentDetail = new AnhuiInsuranceParticipation.PaymentDetail();
            paymentDetail.setInsuranceType(cellList.get(0));
            paymentDetail.setStartTime(cellList.get(1));
            paymentDetail.setEndTime(cellList.get(2));
            paymentDetail.setPaymentBase(cellList.get(3));
            paymentDetail.setUnitName(cellList.get(4));
            paymentDetail.setIndividualPayableAmount(cellList.get(5));
            paymentDetail.setPaymentStatus(cellList.get(6));
            paymentDetail.setInsuredPlace(cellList.get(7));
            paymentDetailList.add(paymentDetail);
        }

        anhuiInsuranceParticipation.setPaymentDetailList(paymentDetailList);
    }

    private List<List<String>> parseFileToRowList(String filePath) {
        // 1. 读取文件
        File pdf = new File(filePath);

        //页面所有table的记录，每一个元素代表下面一条记录cellList
        List<List<String>> rowList = new ArrayList<>();

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf)) {
            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            SpreadsheetDetectionAlgorithm detectionAlgorithm = new SpreadsheetDetectionAlgorithm();
            Map<Integer, List<Rectangle>> pageNumber2RectangleListMap = new HashMap<>();//key为页的序号， value为对应的Rectangle的list

            // 4. 获取每页的PageIterator
            PageIterator pageIterator = objectExtractor.extract();

            // 5. 解析每页的Rectangle
            // 如果单页pdf中有多个Rectangle，则解析出来的List<Rectangle>会有多个对象
            while (pageIterator.hasNext()) {
                Page page = pageIterator.next();
                List<Rectangle> rectangleList = detectionAlgorithm.detect(page);
                if (rectangleList.size() > 0) {
                    pageNumber2RectangleListMap.put(page.getPageNumber(), rectangleList);
                }
            }

            // 6.通过table位置获取表格具体内容
            SpreadsheetExtractionAlgorithm extractionAlgorithm = new SpreadsheetExtractionAlgorithm();

            // 如果单页pdf中有多个表格，则解析出来的List<Rectangle>会有多个对象
            for (Map.Entry<Integer, List<Rectangle>> entry : pageNumber2RectangleListMap.entrySet()) {
                Page page = objectExtractor.extract(entry.getKey());
                Rectangle rectangle = null;

                List<Rectangle> rectangleList = entry.getValue();
                for (Rectangle r : rectangleList) {
                    double rectangleHeight = r.getHeight();
                    if (Double.compare(rectangleHeight, 0) > 0) {
                        rectangle = r;
                        break;
                    }
                }
                if (rectangle == null) {
                    throw new RuntimeException("rectangle is null.");
                }

                if (entry.getKey() > 1) {
                    rectangle.setTop(rectangle.getTop());
                }
                rectangle.setBottom(rectangle.getBottom());
                Page area = page.getArea(rectangle);

                // 如果每页有多个表格，解析每一个table
                List<Table> tableList = extractionAlgorithm.extract(area);
                for (Table table : tableList) {
                    for (int i = 0; i < table.getRowCount(); i++) {
                        List<String> cellList = new ArrayList<>();//一条记录，每个单元格占一个元素
                        for (int j = 0; j < table.getColCount(); j++) {
                            cellList.add(table.getCell(i, j).getText(false));
                        }
                        rowList.add(cellList);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return rowList;
    }

    public static void main(String[] args) {
//        String filePath = "D:\\data\\file\\socialsecurity\\安徽\\zd47iaqw1769097079799181312_bfaa544d50e1761d8df26be3cbbba904_app-gjzwfw-dzsb_origins\\app-gjzwfw-dzsb_cbzm.pdf";
//        AnhuiSocialSecurityPdfParser anhuiSocialSecurityPdfParser = new AnhuiSocialSecurityPdfParser();
//        String json = anhuiSocialSecurityPdfParser.parseAnhuiSocialSecurityPdfToJson("", filePath).getData();
//        System.out.println(json);
    }

}
